package javase.javase02.networkprograming;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Scanner;

/**
 * @author: Gan
 * @date 2021/4/23 0023 16:42
 * @description:
 * UDP
 **/
public class Sender {
    public static void main(String[] args) throws IOException {
        //创建一个UDP连接，一个端口号
        DatagramSocket datagramSocket = new DatagramSocket(54321);
        //接盘录入，接收数据。
        Scanner scanner = new Scanner(System.in);

        while (true) {
            String s = scanner.nextLine();
            //  封装数据并发送
            DatagramPacket senderPacket =
                    NetworkUtils.getSenderPacket("192.168.3.130", 11111, s);
            datagramSocket.send(senderPacket);

            // 用于接收的
            DatagramPacket receiverPacket = NetworkUtils.getReceiverPacket();
            datagramSocket.receive(receiverPacket);
            //将收到的数据解析
            String receiveMsg = NetworkUtils.parsePacket(receiverPacket);
            System.out.println(receiveMsg);
            if (s.equals("bye")) {
                break;
            }
        }
        // close
        datagramSocket.close();
    }
}
